export class StringHelper {
  private constructor() {}

  // 去除零宽字符
  public static removeZeroWidthChar(text: string) {
    const regex = /[\u200B-\u200D\u2060\uFEFF\u202C\u202A]/g;
    return text.replace(regex, '');
  }

  // 获取最后一行文本
  public static getLastLine(str: string) {
    const lines = str.trim().split('\n');
    return lines[lines.length - 1];
  }

  // 时间转换为时间戳
  public static dateStringToTimeStamp(date: string) {
    return Date.parse(date);
  }

  // =?UTF-8?B? base64解码
  public static decodeBase64(str: string, encoding = 'utf-8') {
    const bytes = Uint8Array.from(Buffer.from(str, 'base64'));
    const decoder = new TextDecoder(encoding);
    const decodedText = decoder.decode(bytes);
    return decodedText;
  }

  // =?UTF-8?Q? quote解码
  public static decodeQuote(str: string) {
    const urlString = str.replace(/=([a-z\d]{2})/gi, '%$1');
    try {
      const decodeString = decodeURIComponent(urlString);
      return this.removeZeroWidthChar(decodeString);
    } catch (e) {
      return str;
    }
  }

  // decode header
  public static decodeHeader(str: string) {
    // base64 & quote
    let regex = /\s*=\?(?<encoding>utf-8|gb2312)\?(?<type>b|q)\?(?<text>.*?)\?=/gi;
    str = str.replace(regex, (substring: string, encoding, type, text, from) => {
      type = type?.toUpperCase();
      if (type === 'Q') {
        return this.decodeQuote(text);
      }
      if (type === 'B') {
        return this.decodeBase64(text, encoding);
      }
      return substring;
    });
    return str;
  }
}
